<?php
namespace Admin\Controller;

use Admin\Model\Admin;
use Common\Model\Order;
use Think\Controller;

/**
 * 登录、注销等功能
 * @author  qinshan
 * @since   1.0
 */
class DefaultController extends Controller
{
    public function index()
    {
        /*左连接查询
        $sql = 'SELECT o.*,u.username user_username,m.name movie_name, m.cover movie_cover
              FROM pre_order o
              LEFT JOIN pre_user u ON u.id = o.user_id
              LEFT JOIN pre_movie m ON m.id = o.movie_id';

        $arr = M()->query($sql);
        var_dump($arr);
        */

        $orderArray = M('Order')->select();
        $this->assign('orders', $orderArray);
        //var_dump($orderArray);exit;
        // echo $orderArray[0]['movie_id'];exit;

        /*
        $arr = array(
            array('id'=>1,'name'=>'Summer'),
            array('id'=>2,'name'=>'Ethan'),
        );

        $arr = array(
            new User(1,'Summer'),
            new User(2,'Ethan'),
        );
        */


        //将数组封装为对象
        $orderObjects = array();
        foreach ($orderArray as $row) {
            $temp = new Order();
            $temp->load($row);
            $orderObjects[] = $temp;
        }
        $this->assign('orderObjects', $orderObjects);

        // var_dump($orderObjects);
        //echo $orderObjects[0]->movie_id;
        // exit;


        $this->display();

    }

    public function login()
    {
        //处理登录请求
        if (!empty($_POST)) {

            //$username =$_POST['username'];
            $username = isset($_POST['username']) ? $_POST['username'] : '';
            $password = isset($_POST['password']) ? $_POST['password'] : '';

            if (Admin::login($username, $password)) {

                //登录成功
                $returnUrl = session('returnUrl');
                if (!empty($returnUrl)) {
                    //登录拦截时记录的url (哪里来，回哪里)
                    header('Location:' . $returnUrl);
                } else {
                    //跳去admin的首页
                    $this->redirect('Index/index');
                }
                return;
            }

            $this->assign('message', '用户名或密码不匹配');
        }

        //显示登录界面
        $this->display();
    }

    public function loginout()
    {
        //销毁session
        session('admin.id',null);
        session('admin.username',null);
        $this->redirect('login');
    }
}